<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @expand-change="expandChanges"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <!-- <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.task_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template> -->
      
      <template #expand="{row}">
        <avue-crud :option="expandOption" :data="expandData">
            <template #menu="{row,index,size}">
              <el-button     v-if="row.status<3" type="primary" size="small" icon="el-icon-plus" class="el-button el-button--text el-button--small" @click="addViaStation(row)"  >插入</el-button>
              
              <el-button     v-if="row.type==2 && row.status<1" type="primary" size="small" icon="el-icon-delete" class="el-button el-button--text el-button--small" @click="removeViaStation(row)" >移除</el-button>
              
            </template>
        </avue-crud>
      </template>
    </avue-crud>
     <el-dialog title="插入途经站"
                   append-to-body
                   :visible.sync="viaAddBox"
                   width="500px">
        <el-form ref="form" :model="viaForm" label-width="90px">
           <el-form-item label="当前站点：">
            {{viaForm.name}}  <el-tag size="small">{{viaForm.typeName}}</el-tag> 
          </el-form-item>
            <el-form-item label="插入方式：">
            <el-radio-group v-model="viaForm.flag">
              <el-radio label="当前站点之前" v-if="viaForm.type!=1" ></el-radio>
              <el-radio label="当前站点之后" v-if="viaForm.type!=3" ></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="插入站点：">
            <el-select v-model="viaForm.addStationId" placeholder="请选择站点">
              <el-option
                v-for="item in stations"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="viaAddBox = false">取 消</el-button>
            <el-button type="primary"
                       @click="confirmAddViaStation">确 定</el-button>
          </span>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove,getStationList,addStation,removeStation} from "@/api/ems/task";
  
  import {getList as getStations} from "@/api/ems/station";
  import {getDeptTree} from "@/api/system/dept";
  import {mapGetters} from "vuex";
  import website from '@/config/website';
  import {getDate} from "@/util/date.js";

  export default {
    data() {
      return {
        stations:[],
        viaAddBox:false,
        viaForm:{},
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: false,
          selection: false,
          dialogClickModal: false,
          menu:false,
          menuWidth:0,
          searchIndex:3,
          searchIcon:true,  
          refreshBtn:true,
          columnBtn:true,
          viewBtn:false,
          defaultSort:{
            prop: 'taskTime',
            order: 'descending'
          },
          expand: true,
          expandRowKeys:[],
          rowKey:'id',
          column: [
             {
              label: "状态",
              prop: "status",
               search:true,
              type: "select",
              width: 80,
              dicData: [
                {
                  label: "待出车",
                  value: 1
                },
                {
                  label: "司机签到",
                  value: 2
                },
                {
                  label: "已出车",
                  value: 3
                },
                {
                  label: "已结束",
                  value: 4
                },
                {
                  label: "异常结束",
                  value: 9
                },
              ],               
             
            },
            {
              label: "线路名称",
              prop: "lineName",
              sortable:true,
              width: 140,
              rules: [{
                required: true,
                message: "请输入线路名称",
                trigger: "blur"
              }]
            },
            {
              label: "所属车队",
              prop: "deptId",
              type: "tree",
              multiple: false,
              search:true,
              defaultExpandAll: true,//默认展示
              dicData: [],
              sortable:true,
              width: 120,
              props: {
                label: "title"
              },
              checkStrictly: true,
              slot: true,
              rules: [{
                required: true,
                message: "请选择所车队",
                trigger: "click"
              }]
            },
            {
              label: "车辆ID",
              prop: "vehicleId",
              hide: true,
              rules: [{
                required: true,
                message: "请输入车辆ID",
                trigger: "blur"
              }]
            },
            {
              label: "司机ID",
              prop: "driverId",
              hide: true,
              rules: [{
                required: true,
                message: "请输入司机ID",
                trigger: "blur"
              }]
            },
            {
              label: "车牌号",
              prop: "plateNumber",
              search:true,
              width: 80,
              rules: [{
                required: true,
                message: "请输入车牌号",
                trigger: "blur"
              }]
            },
            {
              label: "自编号",
              prop: "vehicleCode",
              search:true,
              width: 80,
              rules: [{
                required: false,
                message: "请输入车辆编号",
                trigger: "blur"
              }]
            },
            {
              label: "驾驶员",
              prop: "driverName",
              search:true,
              width: 80,
              rules: [{
                required: true,
                message: "请输入司机名称",
                trigger: "blur"
              }]
            },
            {
              label: "手机号",
              prop: "driverPhone",
              search:true,
              sortable:true,
              width: 100,
              rules: [{
                required: true,
                message: "请输入司机手机号",
                trigger: "blur"
              }]
            },
            {
              label: "核载人数",
              prop: "vehicleSeats",
              width: 70,
              rules: [{
                required: true,
                message: "请输入车辆核载人数",
                trigger: "blur"
              }]
            },
            // {
            //   label: "线路编号",
            //   prop: "lineCode",
            //   rules: [{
            //     required: true,
            //     message: "请输入线路编号",
            //     trigger: "blur"
            //   }]
            // },
            // {
            //   label: "趟次编号",
            //   prop: "taskCode",
            //   rules: [{
            //     required: true,
            //     message: "请输入趟次编号（编码规则：yyyymmdd-车编号-01...99)",
            //     trigger: "blur"
            //   }]
            // },
            {
              label: "调度时间",
              prop: "taskTime",
              search:true,
              sortable:true,
              width: 140,
              type: 'datetime',
              searchSpan: 12,
              searchRange: true,
              format: "yyyy-MM-dd HH:mm",
              valueFormat: "yyyy-MM-dd HH:mm",    
              rules: [{
                required: false,
                message: "请输入出车时间",
                trigger: "blur"
              }]
            },
            {
              label: "发车时间",
              prop: "startTime",
              search:false,
              sortable:true,
              width: 140,
              rules: [{
                required: false,
                message: "请输入实际发车时间",
                trigger: "blur"
              }]
            },
            {
              label: "完成时间",
              prop: "finishTime",
              width: 140,
              rules: [{
                required: false,
                message: "请输入实际完成时间",
                trigger: "blur"
              }]
            },
            {
              label: "站载统计",
              prop: "total",
              width: 80,
            },
          ]
        },
        data: [],
        expandOption:{
         calcHeight:0,
          height:300,
          searchShow: false,
          tip: false,
          border: true,
          selection: false,
          menu:true,
          menuWidth:180,
          menuAlign:'left',
          index:false,
          refreshBtn:false,
          columnBtn:false,
          addBtn:false,
          addBtnText:"",
          editBtn:false,
          delBtn:false,
          viewBtn:true,
                         
          column: [
             {
              label: "路由",
              prop: "sort",
              width: 60,
            },
            {
              label: "站点名称",
              width:100,
              prop: "name",
            },
            {
              label: "站点类型",
              prop: "type",
              type: "select",
              width: 80,
              dicData: [
                {
                  label: "首发站",
                  value: 1
                },
                {
                  label: "途经站",
                  value: 2
                },
                {
                  label: "末站",
                  value: 3
                },
              ],                 
            },
            {
              label: "状态",
              prop: "status",
               search:true,
              type: "select",
              width: 80,
              dicData: [
                {
                  label: "未开始",
                  value: 0
                },
                {
                  label: "前往中",
                  value: 1
                },
                {
                  label: "司机签到",
                  value: 2
                },
                {
                  label: "已出站",
                  value: 3
                },
                {
                  label: "已出站",
                  value: 30
                },
                {
                  label: "已出站",
                  value: 31
                },
                {
                  label: "已出站",
                  value: 32
                },
                 {
                  label: "已出站",
                  value: 33
                },
              ],               
             
            },
            {
              label: "签到时间",
              prop: "driverTime",
              width: 80,
              type: "datetime",
              format: "HH:mm:ss",
              valueFormat: "HH:mm:ss",    
            },
            {
              label: "发车时间",
              prop: "checkOutTime",
              width: 80,
              type: "datetime",
              format: "HH:mm:ss",
              valueFormat: "HH:mm:ss",    
            },
            {
              label: "安检时间",
              prop: "securityTime",
              width: 80,
              type: "datetime",
              format: "HH:mm:ss",
              valueFormat: "HH:mm:ss",    
            },
       
            {
              label: "实载人数",
              prop: "checkOutCnt",
                width: 80,
              type: "number",
            },
            {
              label: "人数(全票)",
              prop: "checkOutCnt1",
                width: 80,
              type: "number",
            },
            {
              label: "人数(半票)",
              prop: "checkOutCnt2",
                width: 80,
              type: "number",
            },
            {
              label: "人数(免票)",
              prop: "checkOutCnt3",
                width: 80,
              type: "number",
            },
            {
              label: "行车员",
              prop: "checkUser",
              width: 80,
            },
            {
              label: "行车员电话",
              prop: "checkPhone",
              width: 80,
              hide:true,
            },
            {
              label: "安检员",
              prop: "securityUser",
              width: 80,
            },
            {
              label: "安检员电话",
              prop: "securityPhone",
              width: 80,
              hide:true,
            },
            {
              label: "安全告知",
              prop: "checkOutBefore",
              width: 80,
              hide:true,
            },
            {
              label: "行车三检",
              prop: "checkOutThree",
              width: 80,
              hide:true,
            },
            {
              label: "安检信息",
              prop: "checkOutSecurity",
              width: 80,
              hide:true,
            },
          ]
        },
        expandData:[],
      };
    },
    mounted() {
      // 非租户模式默认加载管理组数据
      if (!website.tenantMode) {
         this.initData(website.tenantId)
      }
       getStations(1, 100, {}).then(res => {
          const data = res.data.data;
          this.stations= data.records
        });
    },    
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: false,
          viewBtn: true,
          delBtn: false,
          editBtn: false
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      initData(tenantId) {
        getDeptTree(tenantId).then(res => {
          const column = this.findObject(this.option.column, "deptId");
          column.dicData = res.data.data;
        });
      },
      expandGetData(id){
         getStationList(id).then(res => {
                const data = res.data.data;
                this.expandData = data
              });
      },
       expandChanges(row, expendList) {
        this.expandData=[];
        
        if (expendList.length) {
            this.option.expandRowKeys = []
            if (row) {
              this.option.expandRowKeys.push(row.id)
              this.expandGetData(row.id)
            }
          } else {
            this.option.expandRowKeys = []
          }
          //this.$message.success('展开回调')
     },
    addViaStation(row){
      this.viaForm={}
      this.viaForm.taskId=row.taskId
      this.viaForm.id=row.id
      this.viaForm.stationId=row.stationId
      this.viaForm.name=row.name
      this.viaForm.type=row.type
      this.viaForm.typeName=(row.type==1?"首站":(row.type==3?"末站":"途经站"))
      this.viaAddBox=true
    },
    confirmAddViaStation(){
      if(!this.viaForm.flag){
        this.$message({
            type: "alert",
            message: "请选择要插入方式!"
          });
        return;
      }
      if(!this.viaForm.addStationId){
        this.$message({
            type: "alert",
            message: "请选择要插入站点!"
          });
        return;
      }
      if(this.viaForm.addStationId==this.viaForm.stationId){
        this.$message({
            type: "alert",
            message: "不能与当前站点相同!"
          });
        return;
      }

      this.viaForm.addType=(this.viaForm.flag=="当前站点之前"?1:2)
      addStation(this.viaForm).then(() => {
          this.onLoad(this.page);
          this.expandGetData(this.viaForm.taskId)
          this.viaAddBox=false
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
    },
    removeViaStation(row){
       this.$confirm("确定要移除该站点吗?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return removeStation(row.taskId, row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.expandGetData(row.taskId)
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
    },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        let query= Object.assign(params, this.query)

        if(query.taskTime && query.taskTime.length>0){
            query.taskTimeStart=query.taskTime[0];
            query.taskTimeEnd=query.taskTime[1];
           delete query.taskTime;
        }else{
            query.taskTimeStart=getDate(-7) + " 00:00";
            query.taskTimeEnd=getDate(7) + " 23:59";
        } 

        getList(page.currentPage, page.pageSize, query).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>
 <style lang="scss" scoped>
    ::v-deep .avue-crud__menu {
      display: none;
    }
 </style>

